import { Route, router } from '@/router'
import { assign, defaultsDeep } from 'lodash-es'
import { VNode, h, render } from 'vue'
import Main from './template/main'

/*
visible 是否展示 boolean
content 展示信息 string
duration 多久后关闭 number
callback 回调函数 function
backHome 如果有duration 时间到后是否返回首页 boolean
 */
interface LoadingConfig {
  visible?: boolean
  content?: string
  duration?: number
  callback?: () => void
  backHome?: boolean
}

//默认配置
const defaultConfig: LoadingConfig = {
  visible: true, //是否显示
  content: 'describe',
  duration: -1,
  backHome: false
}
//返回首页
const back2home = () => {
  router.replace({ name: Route.COMPETITION })
}

let container: HTMLElement
let vNode: VNode

export const useLoading = (options?: LoadingConfig | string) => {
  let config: LoadingConfig = {}

  if (typeof options === 'string') {
    defaultsDeep(config, defaultConfig)
    config.content = options
  } else {
    defaultsDeep(config, options, defaultConfig)
  }

  const loadingBox = document.querySelector('#custom-loading')
  if (!loadingBox) {
    vNode = h(Main, config) // 创建一个节点
    container = document.createElement('div')
    container.id = 'custom-loading'
    document.body.appendChild(container)

    render(vNode, container)
  }

  const destroy = () => {
    document.body.removeChild(container)
  }

  const update = (data: Partial<LoadingConfig>) => {
    assign(vNode?.component?.props, data)
  }

  if (config.duration && config.duration >= 0) {
    //延时大于0 时间到后 自动关闭
    setTimeout(() => {
      if (config.backHome) {
        destroy()
        back2home()
      }
    }, config.duration)
  }

  return { destroy, update }
}
